package com.situ.web.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Banji;
import com.situ.web.service.impl.BanjiServiceImpl;
import com.situ.web.util.JDBCUtil;

@WebServlet("/banji")
public class BanjiServlet extends HttpServlet{
	private BanjiServiceImpl banjiService = new BanjiServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		if(method == null || "".equals(method)) {
			method = "selectAll";
		}
		switch(method) {
		case "selectAll":
			selectAll(req, resp);
			break;
		case "delete":
			delete(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "selectId":
			selectId(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		default:
			break;
		}
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		
		Banji banji = new Banji(Integer.parseInt(id), name);
		boolean isSuccess = banjiService.update(banji);
		resp.sendRedirect(req.getContextPath() + "/banji?method=selectAll");
	}

	private void selectId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		
		Banji banji = banjiService.selectId(Integer.parseInt(id));
		
		req.setAttribute("banji", banji);
		req.getRequestDispatcher("/banji_update.jsp").forward(req, resp);
	}

	private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		Banji banji = new Banji(Integer.parseInt(id), name);
		
		boolean isSuccess = banjiService.insert(banji);
		System.out.println(isSuccess);
		resp.sendRedirect(req.getContextPath() + "/banji?method=selectAll");
	}

	private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		
		boolean isSuccess = banjiService.delete(Integer.parseInt(id));
		System.out.println(isSuccess);
		
		resp.sendRedirect(req.getContextPath() + "/banji?method=selectAll");
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Banji> list = banjiService.selectAll();
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("banji_list.jsp").forward(req, resp);
		
	}
	

}
